<script setup>
import { queryStudentPaper, updateStudentPaper } from '../../api/sysStudentAnswerSheet/sysStudentAnswerSheet.ts';
import { ElMessage,ElMessageBox } from 'element-plus';
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();

// --- 响应式状态 ---
const loading = ref(true);
const data = ref(null);
const textOptions = ref([]); // 存储主观题
const singleOPtions = ref([])
const multipleOPtions = ref([])
const judgeOptions = ref([])
const timeTaken = ref({ minutes: 0, seconds: 0 });

// --- 路由参数 ---
const id = ref(route.query.id);

// 计算属性：根据状态码返回可读的文本
const stateText = computed(() => {
  switch (data.value?.state) {
    case 1:
      return '未开始';
    case 2:
      return '进行中';
    case 3:
      return '等待批改';
    case 4:
      return '已批改';
    default:
      return '未知状态';
  }
});

// 获取数据
const getData = () => {
  loading.value = true;
  queryStudentPaper({ id: id.value }).then(res => {
    data.value = res.data[0];
    console.log("a:",data.value);
    if (data.value && data.value.timeTaken !== undefined) {
      const { minutes, seconds } = formatSeconds(data.value.timeTaken);
      timeTaken.value = { minutes, seconds };
    }
    getQuestionCategory(data.value.content);
  }).catch(err => {
    ElMessage.error('获取试卷失败: ' + (err.message || '未知错误'));
  }).finally(() => {
    loading.value = false;
  });
};

// 题目分类方法
const getQuestionCategory = (questions) => {
  textOptions.value = []; // 清空之前的数据
  singleOPtions.value = []
  multipleOPtions.value  = []
  judgeOptions.value = []
  questions.forEach((item) => {
    if (item.type === 'single') {
      singleOPtions.value.push(item)
    } else if (item.type === 'multiple') {
      multipleOPtions.value.push(item)
    } else if (item.type === "judge"){
      judgeOptions.value.push(item)
    } else if (!questions.type) {
      textOptions.value.push(item)
    }
  });
  // questions.forEach((item) => {
  //   if (item.type === 'single' || item.type === 'multiple' || item.type === "judge") {
  //     // 客观题，暂不处理
  //   } else {
  //     textOptions.value.push(item);
  //   }
  // });
  console.log("主观:", textOptions.value);
};

// 获取剩余时间计时方法
function formatSeconds(totalSeconds) {
  const minutes = Math.floor(totalSeconds / 60);
  const seconds = totalSeconds % 60;
  return { minutes, seconds };
}


const cilckMain = () => {
  // 计算主观题得分
  let sum = 0;
  textOptions.value.forEach(item => {
    console.log("item:",item.sum)
    sum += item.sum
  })
  console.log("sum:", sum)
  data.value.subjTestScores = sum

  // 计算总分
  data.value.totalScores =  data.value.subjTestScores + data.value.objectiveTestScores;

  // 合并content
  const list = []
  list.push(...singleOPtions.value)
  list.push(...multipleOPtions.value)
  list.push(...judgeOptions.value)
  list.push(...textOptions.value)
  data.value.content = list

  // 修改状态(已完成)
  data.value.state = 4;
  console.log("data:",data.value)

  // 修改源数据
  updateStudentPaper(data.value).then(res => {
    ElMessage.success('提交成功');
    backSubmit();
  }).catch(err => {
    ElMessage.error('提交失败: ' + (err.message || '未知错误'));
  });
}

// 提交
const submitCilck = () => {
  console.log("s:",data.value)
  ElMessageBox.confirm(
      '确认提交?',
      'Warning',
      {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning',
      }
  )
      .then(() => {
        cilckMain();
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '操作取消',
        })
      })
}

// 后退
const backSubmit = () => {
  router.back();
}

onMounted(() => {
  getData();
});
</script>


<template>
  <div v-loading="loading" class="exam-container">
    <el-divider content-position="left">试卷信息</el-divider>
    <el-card v-loading="loading" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="paper-title">{{ data?.tesPaperName || '未命名试卷' }}</span>
          <el-tag :type="data?.state === 3 ? 'success' : 'warning'" effect="plain">
            {{ stateText }}
          </el-tag>
        </div>
      </template>

      <!-- 试卷基本信息 -->
      <el-descriptions :column="3" border>
        <el-descriptions-item label="试卷id">{{ data?.id }}</el-descriptions-item>
        <el-descriptions-item label="模板id">{{ data?.tesPaperId }}</el-descriptions-item>
        <el-descriptions-item label="科目">{{ data?.subject }}</el-descriptions-item>
        <el-descriptions-item label="学生">{{ data?.studentName }}</el-descriptions-item>
        <el-descriptions-item label="教师">{{ data?.teacherName }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ data?.createTime }}</el-descriptions-item>
        <el-descriptions-item label="考试开始时间">{{ data?.testStartTime || '未开始' }}</el-descriptions-item>
        <el-descriptions-item label="提交时间">{{ data?.endTime || '未提交' }}</el-descriptions-item>
        <el-descriptions-item label="考试时长">{{ data?.timeLimit }} 分钟</el-descriptions-item>
        <el-descriptions-item label="用时">
          &nbsp;&nbsp;{{ timeTaken.minutes }}&nbsp;分&nbsp;{{ timeTaken.seconds }}&nbsp;秒
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
    <el-divider content-position="left">主观题</el-divider>

    <!-- 题目信息   -->
      <el-card v-for="(item, index) in textOptions" :key="index" shadow="never">
        <h4>{{index+1}}. {{item.content}}</h4>
        <el-divider content-position="left">学生答题</el-divider>
        <el-input v-model="item.answer" disabled :autosize="{ minRows: 1}" type="textarea" placeholder="Please input"/>
        <el-divider content-position="left">参考答案</el-divider>
        <el-input v-model="item.referenceAnswer" disabled :autosize="{ minRows: 1}" type="textarea" placeholder="Please input"/>
        <el-divider content-position="left">评分标准</el-divider>
        <el-input v-model="item.scoringCriteria" disabled :autosize="{ minRows: 1}" type="textarea" placeholder="Please input"/>
        <el-divider />
        <el-row>
          <el-col :span="2">
            <el-text class="mx-1" type="primary">得分</el-text>
          </el-col>
          <el-col :span="4">
            <el-input-number v-model="item.sum" :min="1" :max="item.score">
              <template #suffix>
                <span>%</span>
              </template>
            </el-input-number>
          </el-col>
        </el-row>
      </el-card>
    <el-affix position="bottom" :offset="20">
      <div style="display: flex; justify-content: flex-end; width: 100%;margin: 30px;">
        <el-button icon="Back" plain @click="backSubmit" style="margin-right: 0; padding: 25px">返回</el-button>
        <el-button icon="Pointer" plain  type="primary" @click="submitCilck" style="margin-right: 30px; padding: 25px">提交</el-button>
      </div>
    </el-affix>
  </div>
</template>

<style scoped lang="scss">
.exam-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-card{
  .el-input{
    width: 100%;
  }
}
</style>